<template>
  <div class="page-warp h-f bg-grey-200" :style="CC_PAGE_STYLE">
    <div class="header-warp" v-if="!isview">
      <div class="sticky-headers bg-white">
        <div class="form-warp bg-white" ref="headerForm">
          <uni-forms
            label-width="0"
            label-align="left"
            ref="formRef"
          >
            <uni-forms-item>
              <button class="uni-btn" type="primary" size="medium" @click="addItem">增行</button>
            </uni-forms-item>
          </uni-forms>
        </div>
      </div>
    </div>

    <div class="f-warp">
      <div class="fillet">
        <span class="fillet__text">上架明细</span>
      </div>
      <div class="form-warp bg-grey-200">
        <stock-item-list
          :data="list.rows"
          @delete="itemDelete"
          :columns="list.columns"
        >
          <template #iipQty="{row}">
              <uni-number-box
                v-model="row['iipQty']"
                :placeholder="b_PLACEHOLDER_STR('上架数量', COM_TYPE.IN)"
                :disabled="isview"
                :min="0"
              />
          </template>
          <template #iipBatch="{row}">
              <uni-easyinput
                v-model="row['iipBatch']"
                :placeholder="b_PLACEHOLDER_STR('批次号', COM_TYPE.IN)"
                :disabled="!is_p_in"
              />
          </template>
          <template #bwaId="{row}">
            <uni-data-select
              :localdata="bwaData.rows"
              v-model="row['bwaId']"
              :placeholder="b_PLACEHOLDER_STR('仓库', COM_TYPE.SELECT)"
              valueKey="bwa_id"
              labelKey="bwa_name"
              @select="bwaChange"
              disabled
            />
          </template>
          <template #bwlId="{row,index}">
            <uni-data-select
              :localdata="bwlData.rows"
              v-model="row['bwlId']"
              :placeholder="b_PLACEHOLDER_STR('库位', COM_TYPE.SELECT)"
              valueKey="bwl_id"
              labelKey="bwl_name"
              :disabled="isview"
              @select="bwlChange($event,row,index)"
            />
          </template>

          <template #menu="{row,index}">
            <div class="btn-rows">
              <button-circle
                type="danger"
                size="mini"
                @click="itemDelete(row,index)"
                v-if="!isview"
              >删除
              </button-circle>
            </div>
          </template>
        </stock-item-list>
      </div>
    </div>

    <div class="form-footer">
      <div class="footer-warp">
        <div class="footer__btn">
          <div class="btn">
            <button class="uni-btn"
                    @click="cancel"
                    :disabled="loading.ILOADING"
            >
              取消
            </button>
          </div>
          <div class="btn" v-if="!isview">
            <button class="uni-btn"
                    type="primary"
                    @click="confirm(0)"
                    :disabled="loading.ILOADING"
                    :loading="loading.ILOADING"

            >
              保存
            </button>
          </div>
        </div>
      </div>
    </div>

    <uni-message-ex custom-nav />

    <!--    <input-item-selector-->
    <!--      ref="biiDialog"-->
    <!--      dialog-only-->
    <!--      event-id="bii-select-dialog"-->
    <!--      page="../../../../dialogs/BiiDialog"-->
    <!--      value-key="bii_id"-->
    <!--      label-key="bii_name"-->
    <!--      @change="biiChange"-->
    <!--      multiple-->
    <!--    ></input-item-selector>-->
  </div>

</template>

<script setup>
import { computed, reactive, ref } from 'vue'
import { onLoad, onReachBottom } from '@dcloudio/uni-app'
import { useLoading } from '../../../../../store/LoadingStore'
import { useStaticTypeDictionaries } from '../../../../../components/StaticDictionary/StaticTypeDictionaries'
import { useMessage } from '../../../../../store/MessageStore'
import { PageUtil } from '../../../../../utils/PageUtil'
import UniMessageEx from '../../../../../components/UniMessageEx.vue'
import { usePageHeaderForm } from '../../../../../hooks/PageHeaderForm'
import StockItemList from '../../../../../components/StockItem/StockItemList.vue'
import { setPageTitle, usePageParamHook } from '../../common/PageParam'
import { useFormServ } from '../../../../../hooks/FormServ'
import moment, { Ls } from 'dayjs'
import ButtonCircle from '../../../../../components/ButtonCircle.vue'
import { useDictionaryStore } from '../../../../../store/DictionaryStore'
import { StringUtils } from '../../../../../utils/StringUtils'

//#region Refs
const headerForm = ref(null)
const formRef = ref(null)
const biiDialog = ref(null)
//#endregion Refs


//#region Const


//#endregion Const

//#region Use
const {
  setupPage
} = usePageParamHook()
const {
  COM_TYPE,
  b_PLACEHOLDER_STR
} = useFormServ()
const {
  KEYS
} = useStaticTypeDictionaries()
const loading = useLoading()
const msgStore = useMessage()

const dictStore = useDictionaryStore()

const { CC_PAGE_STYLE } = usePageHeaderForm(headerForm)
//#endregion Use


//#region Data
const pageParams = ref({})
const form = reactive({})
const is_p_in = computed(() => {
  const { isPIn = false } = pageParams.value
  return isPIn
})

const list = reactive({
  rows: [],
  columns: [
    { label: '存货编码', prop: 'biiCode' },
    { label: '存货名称', prop: 'biiName' },
    { label: '规格型号', prop: 'biiSpec' },
    { label: '仓库', prop: 'bwaId', slot: true, required: true },
    { label: '库位', prop: 'bwlId', slot: true, required: true },
    { label: '上架数量', prop: 'iipQty', slot: true, required: true },
    { label: '批次号', prop: 'iipBatch',slot: true, required: is_p_in  }
    // { label: '库存量', prop: 'isiQty' }
  ]
})

const bwlData = reactive({
  rows: []
})

const bwaData = reactive({
  rows: []
})

const isview = computed(() => {
  const { __view = false } = pageParams.value
  return __view
})
//#endregion Data

//#region Method

const bwaChange = function(row) {
  const { bwa_id } = row

  dictStore.getBwlList({
    limit: -1,
    size: -1,
    bwa_id,
    bwl_state: 1
  }).then(res => {
    const { Rows = [] } = res || {}
    bwlData.rows = Rows
  })
}

const bwlChange = function(e,row,index) {
  list.rows[index].bwlName = e['bwl_name']
  list.rows[index].bwlCode = e['bwl_code']
}

const queryData = function() {
  dictStore.getBwaList({
    limit: -1,
    size: -1,
    bwa_state: 1
  }).then(res => {
    const { Rows = [] } = res || {}
    bwaData.rows = Rows
  })
  if (!isview.value) {
   if(list.rows.length){
     list.rows.map(x => {
      const { bwaId: bwa_id } = x
      dictStore.getBwlList({
        limit: -1,
        size: -1,
        bwa_id,
        bwl_state: 1
      }).then(res => {
        const { Rows = [] } = res || {}
        bwlData.rows = Rows
      })
    })
   }else{
     dictStore.getBwlList({
        limit: -1,
        size: -1,
        bwa_id:form.bwaId,
        bwl_state: 1
      }).then(res => {
        const { Rows = [] } = res || {}
        bwlData.rows = Rows
      })
   }
  } else {
    dictStore.getBwlList({
      limit: -1,
      size: -1,
      bwl_state: 1
    }).then(res => {
      const { Rows = [] } = res || {}
      bwlData.rows = Rows
    })
  }
}

const addItem = function() {
  const {
    bii_code: biiCode,
    bii_id: biiId,
    bii_name: biiName,
    bii_type: biiType,
    bii_spec: biiSpec,
    bu_name: buName,
    bwaId,
  } = form
  const batch = [
    biiCode,
    moment().format('YYYYMMDD')
  ].join('')
  list.rows.push({
    biiCode,
    biiId,
    biiType,
    biiName,
    biiSpec,
    buName,
    bwaId,
    iipQty: 1,
    iipBatch: batch
  })
}

const itemDelete = function(row, index) {
  list.rows.splice(index, 1)
}

const cancel = function() {
  PageUtil.back()
}

const confirm = function() {
  console.log(list.rows)
  if (!list.rows.length) {
    msgStore.error('无上架明细')

    return
  }
  let sum = 0

  const empty = []
  const nerr = []
  list.rows.map(x => {
    sum += parseFloat(x['iipQty'])


    if (StringUtils.isEmptyOrNull(x['bwaId'])) {
      empty.push(1)
    } else if (StringUtils.isEmptyOrNull(x['bwlId'])) {
      empty.push(1)
    } else if (StringUtils.isEmptyOrNull(x['iipQty'])) {
      empty.push(1)
    } else if (StringUtils.isEmptyOrNull(x['iipBatch'] && is_p_in.value)) {
      // 成品入库批次号必填，其他入库批次号不是必填
      empty.push(1)
    }

    if (StringUtils.getNumber(nerr, 2, null) === null) {
      nerr.push(1)
    }
  })
  if (empty.length) {
    msgStore.error('必填字段不能为空')
    return
  }

  if (nerr.length) {
    msgStore.error('上架数量有误, 请重新输入')
    return
  }
  PageUtil.emitPageEvent({ list: list.rows || [], iipQty: sum, form: form })
  PageUtil.back()
}
//#endregion Method


//#region Page Events
onLoad((params) => {
  let _p = PageUtil.parseParam(params)
  let { row: p } = _p
  Object.entries(p).forEach(([key, value]) => {
    form[key] = value
    pageParams.value[key] = value
  })
  const { PAGE_HOOK_PARAM, putList = [] } = form

  setupPage(PAGE_HOOK_PARAM)
  setPageTitle(PAGE_HOOK_PARAM, '明细')
  list.rows = putList || []
  queryData()

  console.log('item load page', form)
  console.log(list.rows)
})

onReachBottom(() => {
  console.log('bottom')
})
//#endregion Page Events

</script>

<style lang="scss" scoped>
@import "@/assets/PageCommon.scss";
@import "@/assets/PageHeaderForm.scss";


.page-warp {
  .header-warp {
    &:after {
      height: 0;
    }

    .form-warp {
      padding: 0 12px;
      padding-right: 0;
    }
  }

  .f-warp {
    .form-warp {
      padding-bottom: 12px;
    }
  }

  .form-footer {
    height: 60px;
  }
}

.ct-end {
  display: flex;
  justify-content: flex-end;
  margin-right: 12px;

  .len-md {
    min-width: 20%;

    .ct-btn {
      width: 100%;
    }
  }
}

::v-deep(.capture-selector) {

  .s-list {
    overflow: hidden;

    .s-item {

      border-bottom: 1px solid #e5f1fc;
      text-align: center;
      position: relative;

      .item__btn {
        height: 100%;
        width: 100%;
        display: inline-block;
        padding: 22rpx 0rpx;
      }
    }
  }
}

.inside__input {
  ::v-deep.uni-numbox__value {
    height: 21px !important;
  }

  ::v-deep.uni-select {
    height: 21px !important;
  }
}
</style>
